[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity, isPopulated } from '@growi/core';
  5. import type {
  6. GroupType,
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  8. } from '@growi/core';
  9. import {
  10. isClient, pagePathUtils, pathUtils,
  11. } from '@growi/core/dist/utils';
  12. import ExtensibleCustomError from 'extensible-custom-error';
  13. import type {
  14. GetServerSideProps, GetServerSidePropsContext,
  15. } from 'next';
  16. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  17. import dynamic from 'next/dynamic';
  18. import Head from 'next/head';
  19. import { useRouter } from 'next/router';
  20. import superjson from 'superjson';
  21. import { useEditorModeClassName } from '~/client/services/layout';
  22. import { PageView } from '~/components/Page/PageView';
  23. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  24. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  25. import type { CrowiRequest } from '~/interfaces/crowi-request';
  26. import type { IPageGrantData } from '~/interfaces/page';
  27. import type { RendererConfig } from '~/interfaces/services/renderer';
  28. import type { PageModel, PageDocument } from '~/server/models/page';
  29. import type { PageRedirectModel } from '~/server/models/page-redirect';
  30. import {
  31. useCurrentUser,
  32. useIsForbidden, useIsSharedUser,
  33. useIsEnabledStaleNotification, useIsIdenticalPath,
  34. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  35. useDefaultIndentSize, useIsIndentSizeForced,
  36. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  37. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  38. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  39. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  40. useIsUploadAllFileAllowed, useIsUploadEnabled,
  41. } from '~/stores/context';
  42. import { useEditingMarkdown } from '~/stores/editor';
  43. import {
  44. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  45. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  46. } from '~/stores/page';
  47. import { useRedirectFrom } from '~/stores/page-redirect';
  48. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  49. import { useSelectedGrant } from '~/stores/ui';
  50. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  51. import loggerFactory from '~/utils/logger';
  52. import { BasicLayout } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  54. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  55. import type { NextPageWithLayout } from './_app.page';
  56. import type { CommonProps } from './utils/commons';
  57. import {
  58. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  59. } from './utils/commons';
  60. import styles from './[[...path]].module.scss';
  61. const subnavigationTopBlockClass = styles['subnavigation-top-block'];
  62. declare global {
  63. // eslint-disable-next-line vars-on-top, no-var
  64. var globalEmitter: EventEmitter;
  65. }
  66. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  67. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  68. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  69. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  70. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  71. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  72. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  73. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  74. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  75. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  76. const ConflictDiffModal = dynamic(() => import('../components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  77. const logger = loggerFactory('growi:pages:all');
  78. const {
  79. isPermalink: _isPermalink, isCreatablePage,
  80. } = pagePathUtils;
  81. const { removeHeadingSlash } = pathUtils;
  82. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  83. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  84. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  85. {
  86. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  87. return v?.data != null
  88. && v?.data.toObject != null
  89. && v?.meta != null
  90. && isIPageInfoForEntity(v.meta);
  91. },
  92. serialize: (v) => {
  93. return {
  94. data: superjson.stringify(v.data.toObject()),
  95. meta: superjson.stringify(v.meta),
  96. };
  97. },
  98. deserialize: (v) => {
  99. return {
  100. data: superjson.parse(v.data),
  101. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  102. };
  103. },
  104. },
  105. 'IPageToShowRevisionWithMetaTransformer',
  106. );
  107. // GrowiContextualSubNavigation for NOT shared page
  108. type GrowiContextualSubNavigationProps = {
  109. isLinkSharingDisabled: boolean,
  110. }
  111. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  112. const { isLinkSharingDisabled } = props;
  113. const { data: currentPage } = useSWRxCurrentPage();
  114. return (
  115. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  116. );
  117. };
  118. type Props = CommonProps & {
  119. pageWithMeta: IPageToShowRevisionWithMeta | null,
  120. // pageUser?: any,
  121. redirectFrom?: string;
  122. // shareLinkId?: string;
  123. isLatestRevision?: boolean,
  124. isIdenticalPathPage?: boolean,
  125. isForbidden: boolean,
  126. isNotFound: boolean,
  127. isNotCreatable: boolean,
  128. // isAbleToDeleteCompletely: boolean,
  129. templateTagData?: string[],
  130. templateBodyData?: string,
  131. isSearchServiceConfigured: boolean,
  132. isSearchServiceReachable: boolean,
  133. isSearchScopeChildrenAsDefault: boolean,
  134. isEnabledMarp: boolean,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. noCdn: string,
  141. // highlightJsStyle: string,
  142. isAllReplyShown: boolean,
  143. isContainerFluid: boolean,
  144. isUploadEnabled: boolean,
  145. isUploadAllFileAllowed: boolean,
  146. isEnabledStaleNotification: boolean,
  147. isEnabledAttachTitleHeader: boolean,
  148. // isEnabledLinebreaks: boolean,
  149. // isEnabledLinebreaksInComments: boolean,
  150. adminPreferredIndentSize: number,
  151. isIndentSizeForced: boolean,
  152. disableLinkSharing: boolean,
  153. skipSSR: boolean,
  154. ssrMaxRevisionBodyLength: number,
  155. grantData?: IPageGrantData,
  156. rendererConfig: RendererConfig,
  157. };
  158. const Page: NextPageWithLayout<Props> = (props: Props) => {
  159. // register global EventEmitter
  160. if (isClient() && window.globalEmitter == null) {
  161. window.globalEmitter = new EventEmitter();
  162. }
  163. const router = useRouter();
  164. useCurrentUser(props.currentUser ?? null);
  165. // commons
  166. useCsrfToken(props.csrfToken);
  167. useGrowiCloudUri(props.growiCloudUri);
  168. // page
  169. useIsContainerFluid(props.isContainerFluid);
  170. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  171. useIsForbidden(props.isForbidden);
  172. useIsNotCreatable(props.isNotCreatable);
  173. useRedirectFrom(props.redirectFrom ?? null);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsSearchPage(false);
  178. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  179. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  180. useIsSearchServiceReachable(props.isSearchServiceReachable);
  181. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  182. useIsSlackConfigured(props.isSlackConfigured);
  183. // useIsMailerSetup(props.isMailerSetup);
  184. useIsAclEnabled(props.isAclEnabled);
  185. // useHasSlackConfig(props.hasSlackConfig);
  186. // useNoCdn(props.noCdn);
  187. useDefaultIndentSize(props.adminPreferredIndentSize);
  188. useIsIndentSizeForced(props.isIndentSizeForced);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  192. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  193. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  194. useIsAllReplyShown(props.isAllReplyShown);
  195. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  196. useIsUploadEnabled(props.isUploadEnabled);
  197. const { pageWithMeta } = props;
  198. const pageId = pageWithMeta?.data._id;
  199. const revisionBody = pageWithMeta?.data.revision?.body;
  200. useCurrentPathname(props.currentPathname);
  201. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  202. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  203. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  204. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  205. const { mutate: mutateIsNotFound } = useIsNotFound();
  206. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  207. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  208. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  209. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  210. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  211. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  212. useSetupGlobalSocket();
  213. useSetupGlobalSocketForPage(pageId);
  214. // Store initial data (When revisionBody is not SSR)
  215. useEffect(() => {
  216. if (!props.skipSSR) {
  217. return;
  218. }
  219. if (currentPageId != null && !props.isNotFound) {
  220. const mutatePageData = async() => {
  221. const pageData = await mutateCurrentPage();
  222. mutateEditingMarkdown(pageData?.revision?.body);
  223. };
  224. // If skipSSR is true, use the API to retrieve page data.
  225. // Because pageWIthMeta does not contain revision.body
  226. mutatePageData();
  227. }
  228. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  229. // sync grant data
  230. useEffect(() => {
  231. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  232. mutateSelectedGrant(grantDataToApply);
  233. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  234. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  235. useEffect(() => {
  236. const decodedURI = decodeURI(window.location.pathname);
  237. if (isClient() && decodedURI !== props.currentPathname) {
  238. const { search, hash } = window.location;
  239. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  240. }
  241. }, [props.currentPathname, router]);
  242. // initialize mutateEditingMarkdown only once per page
  243. // need to include useCurrentPathname not useCurrentPagePath
  244. useEffect(() => {
  245. if (props.currentPathname != null) {
  246. mutateEditingMarkdown(revisionBody);
  247. }
  248. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  249. useEffect(() => {
  250. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  251. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  252. useEffect(() => {
  253. mutateCurrentPageId(pageId ?? null);
  254. }, [mutateCurrentPageId, pageId]);
  255. useEffect(() => {
  256. mutateIsNotFound(props.isNotFound);
  257. }, [mutateIsNotFound, props.isNotFound]);
  258. useEffect(() => {
  259. mutateIsLatestRevision(props.isLatestRevision);
  260. }, [mutateIsLatestRevision, props.isLatestRevision]);
  261. useEffect(() => {
  262. mutateTemplateTagData(props.templateTagData);
  263. }, [props.templateTagData, mutateTemplateTagData]);
  264. useEffect(() => {
  265. mutateTemplateBodyData(props.templateBodyData);
  266. }, [props.templateBodyData, mutateTemplateBodyData]);
  267. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  268. // So preferentially take page data from useSWRxCurrentPage
  269. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  270. const title = generateCustomTitleForPage(props, pagePath);
  271. return (
  272. <>
  273. <Head>
  274. <title>{title}</title>
  275. </Head>
  276. <div className="dynamic-layout-root justify-content-between">
  277. <div className={`${subnavigationTopBlockClass} d-block d-md-none border-bottom`}></div>
  278. <nav className="sticky-top">
  279. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  280. </nav>
  281. <DisplaySwitcher
  282. pageView={(
  283. <PageView
  284. pagePath={pagePath}
  285. initialPage={pageWithMeta?.data}
  286. rendererConfig={props.rendererConfig}
  287. />
  288. )}
  289. />
  290. <PageStatusAlert />
  291. </div>
  292. </>
  293. );
  294. };
  295. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  296. const editorModeClassName = useEditorModeClassName();
  297. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  298. };
  299. type LayoutProps = Props & {
  300. children?: ReactNode
  301. }
  302. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  303. // init sidebar config with UserUISettings and sidebarConfig
  304. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  305. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  306. };
  307. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  308. return (
  309. <>
  310. <GrowiPluginsActivator />
  311. <DrawioViewerScript />
  312. <Layout {...page.props}>
  313. {page}
  314. </Layout>
  315. <UnsavedAlertDialog />
  316. <DescendantsPageListModal />
  317. <DrawioModal />
  318. <HandsontableModal />
  319. <QuestionnaireModalManager />
  320. <TemplateModal />
  321. <LinkEditModal />
  322. <TagEditModal />
  323. <ConflictDiffModal />
  324. </>
  325. );
  326. };
  327. function getPageIdFromPathname(currentPathname: string): string | null {
  328. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  329. }
  330. class MultiplePagesHitsError extends ExtensibleCustomError {
  331. pagePath: string;
  332. constructor(pagePath: string) {
  333. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  334. this.pagePath = pagePath;
  335. }
  336. }
  337. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  338. const { model: mongooseModel } = await import('mongoose');
  339. const req: CrowiRequest = context.req as CrowiRequest;
  340. const { crowi } = req;
  341. const { revisionId } = req.query;
  342. const Page = crowi.model('Page') as PageModel;
  343. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  344. const { pageService, configManager, pageGrantService } = crowi;
  345. let currentPathname = props.currentPathname;
  346. const pageId = getPageIdFromPathname(currentPathname);
  347. const isPermalink = _isPermalink(currentPathname);
  348. const { user } = req;
  349. if (!isPermalink) {
  350. // check redirects
  351. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  352. if (chains != null) {
  353. // overwrite currentPathname
  354. currentPathname = chains.end.toPath;
  355. props.currentPathname = currentPathname;
  356. // set redirectFrom
  357. props.redirectFrom = chains.start.fromPath;
  358. }
  359. // check whether the specified page path hits to multiple pages
  360. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  361. if (count > 1) {
  362. throw new MultiplePagesHitsError(currentPathname);
  363. }
  364. }
  365. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  366. const page = pageWithMeta?.data as unknown as PageDocument;
  367. // add user to seen users
  368. if (page != null && user != null) {
  369. await page.seen(user);
  370. }
  371. // populate & check if the revision is latest
  372. if (page != null) {
  373. page.initLatestRevisionField(revisionId);
  374. props.isLatestRevision = page.isLatestRevision();
  375. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  376. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  377. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  378. }
  379. if (page == null && user != null) {
  380. const templateData = await Page.findTemplate(props.currentPathname);
  381. if (templateData != null) {
  382. props.templateTagData = templateData.templateTags as string[];
  383. props.templateBodyData = templateData.templateBody as string;
  384. }
  385. // apply parent page grant, without groups that user isn't related to
  386. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  387. if (ancestor != null) {
  388. ancestor.populate('grantedGroups.item');
  389. const userRelatedGrantedGroups = (await pageGrantService.getUserRelatedGrantedGroups(ancestor, user)).map((group) => {
  390. if (isPopulated(group.item)) {
  391. return {
  392. id: group.item._id,
  393. name: group.item.name,
  394. type: group.type,
  395. };
  396. }
  397. return null;
  398. }).filter((info): info is NonNullable<{id: string, name: string, type: GroupType}> => info != null);
  399. props.grantData = {
  400. grant: ancestor.grant,
  401. userRelatedGrantedGroups,
  402. };
  403. }
  404. }
  405. props.pageWithMeta = pageWithMeta;
  406. }
  407. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  408. const req: CrowiRequest = context.req as CrowiRequest;
  409. const { crowi } = req;
  410. const Page = crowi.model('Page') as PageModel;
  411. const { currentPathname } = props;
  412. const pageId = getPageIdFromPathname(currentPathname);
  413. const isPermalink = _isPermalink(currentPathname);
  414. const page = props.pageWithMeta?.data;
  415. if (props.isIdenticalPathPage) {
  416. props.isNotCreatable = true;
  417. }
  418. else if (page == null) {
  419. props.isNotFound = true;
  420. props.isNotCreatable = !isCreatablePage(currentPathname);
  421. // check the page is forbidden or just does not exist.
  422. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  423. props.isForbidden = count > 0;
  424. }
  425. else {
  426. props.isNotFound = page.isEmpty;
  427. props.isNotCreatable = false;
  428. props.isForbidden = false;
  429. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  430. if (isPermalink && page.isEmpty) {
  431. props.currentPathname = page.path;
  432. }
  433. // /path/to/page ==> /62a88db47fed8b2d94f30000
  434. if (!isPermalink && !page.isEmpty) {
  435. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  436. if (!isToppage) {
  437. props.currentPathname = `/${page._id}`;
  438. }
  439. }
  440. }
  441. }
  442. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  443. // const req: CrowiRequest = context.req as CrowiRequest;
  444. // const { crowi } = req;
  445. // const UserModel = crowi.model('User');
  446. // if (isUserPage(props.currentPagePath)) {
  447. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  448. // if (user != null) {
  449. // props.pageUser = JSON.stringify(user.toObject());
  450. // }
  451. // }
  452. // }
  453. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  454. const req: CrowiRequest = context.req as CrowiRequest;
  455. const { crowi } = req;
  456. const {
  457. searchService, configManager, aclService,
  458. } = crowi;
  459. props.isSearchServiceConfigured = searchService.isConfigured;
  460. props.isSearchServiceReachable = searchService.isReachable;
  461. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  462. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  463. // props.isMailerSetup = mailService.isMailerSetup;
  464. props.isAclEnabled = aclService.isAclEnabled();
  465. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  466. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  467. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  468. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  469. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  470. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  471. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  472. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  473. props.isUploadAllFileAllowed = crowi.fileUploadService.getFileUploadEnabled();
  474. props.isUploadEnabled = crowi.fileUploadService.getIsUploadable();
  475. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  476. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  477. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  478. props.rendererConfig = {
  479. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  480. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  481. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  482. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  483. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  484. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  485. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  486. // XSS Options
  487. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  488. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  489. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  490. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  491. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  492. };
  493. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  494. }
  495. /**
  496. * for Server Side Translations
  497. * @param context
  498. * @param props
  499. * @param namespacesRequired
  500. */
  501. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  502. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  503. props._nextI18Next = nextI18NextConfig._nextI18Next;
  504. }
  505. const getAction = (props: Props): SupportedActionType => {
  506. if (props.isNotCreatable) {
  507. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  508. }
  509. if (props.isForbidden) {
  510. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  511. }
  512. if (props.isNotFound) {
  513. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  514. }
  515. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  516. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  517. }
  518. return SupportedAction.ACTION_PAGE_VIEW;
  519. };
  520. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  521. const req = context.req as CrowiRequest;
  522. const { user } = req;
  523. const result = await getServerSideCommonProps(context);
  524. // check for presence
  525. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  526. if (!('props' in result)) {
  527. throw new Error('invalid getSSP result');
  528. }
  529. const props: Props = result.props as Props;
  530. if (props.redirectDestination != null) {
  531. return {
  532. redirect: {
  533. permanent: false,
  534. destination: props.redirectDestination,
  535. },
  536. };
  537. }
  538. if (user != null) {
  539. props.currentUser = user.toObject();
  540. }
  541. try {
  542. await injectPageData(context, props);
  543. }
  544. catch (err) {
  545. if (err instanceof MultiplePagesHitsError) {
  546. props.isIdenticalPathPage = true;
  547. }
  548. else {
  549. throw err;
  550. }
  551. }
  552. await injectRoutingInformation(context, props);
  553. injectServerConfigurations(context, props);
  554. await injectNextI18NextConfigurations(context, props, ['translation']);
  555. addActivity(context, getAction(props));
  556. return {
  557. props,
  558. };
  559. };
  560. export default Page;